package com.yzh.openai.domain.auth.service;

import com.yzh.openai.domain.auth.model.entity.AuthStateEntity;
import com.yzh.openai.domain.auth.model.entity.UserEntity;
import com.yzh.openai.domain.auth.model.valobj.AuthTypeVO;
import com.yzh.openai.domain.auth.repository.IAuthRepository;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
@Slf4j
@Service
public class AuthService extends AbstractAuthService{
    @Resource
    private IAuthRepository authRepository;

    @Override
    public AuthStateEntity checkCode(String code) {
        //获取验证码校验
        String openId = authRepository.getCode(code);
        if (StringUtils.isBlank(openId)) {
            log.info("鉴权，用户输入的验证码不存在 {}", code);
            return AuthStateEntity.builder()
                    .code(AuthTypeVO.A0001.getCode())
                    .info(AuthTypeVO.A0001.getInfo())
                    .build();
        }
        //删除缓存的值
        authRepository.removeCode(code, openId);
        return AuthStateEntity.builder()
                .code(AuthTypeVO.A0000.getCode())
                .info(AuthTypeVO.A0000.getInfo())
                .openId(openId)
                .build();
    }

    @Override
    public boolean checkToken(String token) {
        return super.isVerify(token);
    }

    @Override
    public String getOpenid(String token) {
        Claims claims = decode(token);
        return claims.get("openId").toString();
    }

    @Override
    public UserEntity queryUserInfo(String token) {
        String openid = getOpenid(token);
        UserEntity userEntity = userRepository.queryUserInfo(openid);
        return userEntity;
    }
}
